package com.adouteam.simple.wechat.service;

import com.adouteam.simple.wechat.base.Constant;
import com.adouteam.simple.wechat.base.WechatConstants;
import com.adouteam.simple.wechat.base.WeixinUrls;
import com.adouteam.simple.wechat.bean.Menu;
import com.adouteam.simple.wechat.bean.WechatResponse;
import com.adouteam.simple.wechat.tool.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * 菜单服务
 *
 * @author buxianglong
 */
public class MenuService{
    public static final Logger logger = LoggerFactory.getLogger(MenuService.class);

    public static String fetchMenu(WechatConstants wechatConstants){
        String fetchWeinxinMenuUrl = WeixinUrls.replace(WeixinUrls.FETCH_MENU, wechatConstants, null);
        try{
            return HttpUtil.get(fetchWeinxinMenuUrl, null,
                    (httpResponse -> EntityUtils.toString(httpResponse.getEntity(), Charset.forName("utf-8"))));
        }catch(Exception e){
            logger.error("Exception when fetchMenu in MenuService", e);
        }
        return "";
    }

    public static Boolean updateMenu(Menu menu, WechatConstants wechatConstants){
        String jsonStr = JSONObject.toJSONString(menu);
        HttpEntity httpEntity = EntityBuilder.create()
                .setText(jsonStr).setContentType(ContentType.APPLICATION_JSON)
                .setContentEncoding(Consts.UTF_8.name())
                .build();
        String url = WeixinUrls.replace(WeixinUrls.UPDATE_MENU, wechatConstants, null);
        return HttpUtil.post(url, null, httpEntity, (httpResponse -> {
            String responseContent = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("utf-8"));
            WechatResponse wechatResponse = JSONObject.parseObject(responseContent, WechatResponse.class);
            logger.debug(Constant.LOGGER_PREFIX + "updateMenu WeixinResponse:" + wechatResponse.toString());
            return wechatResponse.getErrcode() == 0;
        }));
    }
}
